<template>
  <div class="userRegisterView">
    <div id="welcome">
      <h2>欢迎注册</h2>
      已有账号？<a href="/user/login">前往登录</a>
      <br />
      <br />
    </div>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      :model="form"
      @submit="handleSubmit"
      label-align="left"
      auto-label-width
    >
      <a-form-item
        :rules="[
          { required: true, message: '账号不能为空' },
          { minLength: 4, message: '账号长度不能低于四位' },
        ]"
        field="userAccount"
        label="账号"
      >
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>

      <a-form-item
        :rules="[
          { required: true, message: '密码不能为空' },
          { minLength: 8, message: '密码长度不能低于8位' },
        ]"
        field="userPassword"
        label="密码"
        tooltip="密码不少于 8 位"
      >
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>

      <a-form-item
        :rules="[
          { required: true, message: '密码不能为空' },
          { minLength: 8, message: '密码长度不能低于8位' },
        ]"
        field="checkPassword"
        label="请确认密码"
        tooltip="密码不少于 8 位"
      >
        <a-input-password
          v-model="form.checkPassword"
          placeholder="请再次输入密码"
        />
      </a-form-item>

      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          size="large"
          shape="round"
          style="width: 180px; margin-top: 35px; margin-left: 60px"
          >注册
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { UserControllerService, UserRegisterRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import store from "@/store";

const router = useRouter();
const form = reactive<UserRegisterRequest>({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
});

const handleSubmit = async () => {
  if (form.userAccount.length < 4 || form.userPassword.length < 8) {
    return;
  }
  if (
    form.checkPassword.length !== form.userPassword.length ||
    form.checkPassword !== form.userPassword
  ) {
    message.error("两次输入密码不一致");
    return;
  }
  const res = await UserControllerService.userRegisterUsingPost(form);
  if (res.code === 0) {
    message.success("注册成功！");
    await store.dispatch("getLoginUser");
    await router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    message.error("注册失败：" + res.message);
  }
};
</script>

<style scoped>
.userRegisterView {
  border: solid 2px #dddddd;
  border-radius: 4%;
  width: 500px;
  height: 450px;
  background: transparent;
  margin: 0 auto; /*水平居中*/
  margin-top: 20px;
}

#welcome {
  margin-top: 40px;
  margin-left: 30px;
}
</style>
